<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>3-多线程安全问题，线程同步 | Ywrby个人博客网站</title><meta name="keywords" content="Java"><meta name="author" content="Ywrby"><meta name="copyright" content="Ywrby"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="线程安全问题指的是多个线程操作同一个共享资源的时候可能会出现的线程安全问题 银行取钱问题多个用户同时操作一个银行账户进行取钱操作，账户内余额为1000元，每个账户同时取出1000元，由于线程执行的随机性就会导致线程安全问题的产生 银行账户类定义账户内容，定义取钱方法1234567891011121314151617181920212223242526272829303132333435363738">
<meta property="og:type" content="article">
<meta property="og:title" content="3-多线程安全问题，线程同步">
<meta property="og:url" content="http://ywrby.cn/2021/03/03/3-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%EF%BC%8C%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/index.html">
<meta property="og:site_name" content="Ywrby个人博客网站">
<meta property="og:description" content="线程安全问题指的是多个线程操作同一个共享资源的时候可能会出现的线程安全问题 银行取钱问题多个用户同时操作一个银行账户进行取钱操作，账户内余额为1000元，每个账户同时取出1000元，由于线程执行的随机性就会导致线程安全问题的产生 银行账户类定义账户内容，定义取钱方法1234567891011121314151617181920212223242526272829303132333435363738">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://ywrby.cn/img/83821828_p0.jpg">
<meta property="article:published_time" content="2021-03-03T05:59:13.000Z">
<meta property="article:modified_time" content="2021-03-03T07:29:36.000Z">
<meta property="article:author" content="Ywrby">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ywrby.cn/img/83821828_p0.jpg"><link rel="shortcut icon" href="/img/title.png"><link rel="canonical" href="http://ywrby.cn/2021/03/03/3-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%EF%BC%8C%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '3-多线程安全问题，线程同步',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-03-03 15:29:36'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><link rel="stylesheet" href="/css/background.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Ywrby个人博客网站" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/ywrby.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/83821828_p0.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Ywrby个人博客网站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Bilibili</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 追番列表</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://space.bilibili.com/353923033"><i class="fa-fw fas fa-music"></i><span> B站主页</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">3-多线程安全问题，线程同步</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2021-03-03T05:59:13.000Z" title="Created 2021-03-03 13:59:13">2021-03-03</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2021-03-03T07:29:36.000Z" title="Updated 2021-03-03 15:29:36">2021-03-03</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="3-多线程安全问题，线程同步"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="线程安全问题"><a href="#线程安全问题" class="headerlink" title="线程安全问题"></a>线程安全问题</h1><p>指的是多个线程操作同一个共享资源的时候可能会出现的线程安全问题</p>
<h2 id="银行取钱问题"><a href="#银行取钱问题" class="headerlink" title="银行取钱问题"></a>银行取钱问题</h2><p>多个用户同时操作一个银行账户进行取钱操作，账户内余额为1000元，每个账户同时取出1000元，由于线程执行的随机性就会导致线程安全问题的产生</p>
<h3 id="银行账户类"><a href="#银行账户类" class="headerlink" title="银行账户类"></a>银行账户类</h3><h4 id="定义账户内容，定义取钱方法"><a href="#定义账户内容，定义取钱方法" class="headerlink" title="定义账户内容，定义取钱方法"></a>定义账户内容，定义取钱方法</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> ThreadSafety;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//定义账户类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Account</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> cardID;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> Money;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义取钱过程，所有操作这个账户的人都会取走账户中的m元钱</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">DrawMoney</span><span class="params">(<span class="keyword">int</span> m)</span></span>&#123;</span><br><span class="line">        <span class="comment">//判断取钱的用户</span></span><br><span class="line">        String name =Thread.currentThread().getName();</span><br><span class="line">        <span class="comment">//判断余额是否充足</span></span><br><span class="line">        <span class="keyword">if</span>(Money&gt;=m)&#123;</span><br><span class="line">            <span class="comment">//输出取钱结果</span></span><br><span class="line">            System.out.println(name+<span class="string">&quot;用户执行取钱操作，余额充足，支付&quot;</span>+m+<span class="string">&quot;元成功！&quot;</span>);</span><br><span class="line">            <span class="comment">//更新账户余额</span></span><br><span class="line">            Money-=m;</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="comment">//余额不足，取钱失败</span></span><br><span class="line">            System.out.println(name+<span class="string">&quot;用户执行取钱操作，余额不足，支付失败！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(name+<span class="string">&quot;用户结束操作，余额&quot;</span>+Money+<span class="string">&quot;元&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Account</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Account</span><span class="params">(<span class="keyword">int</span> cardID, <span class="keyword">double</span> money)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cardID = cardID;</span><br><span class="line">        Money = money;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getCardID</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cardID;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCardID</span><span class="params">(<span class="keyword">int</span> cardID)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cardID = cardID;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">getMoney</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Money;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMoney</span><span class="params">(<span class="keyword">double</span> money)</span> </span>&#123;</span><br><span class="line">        Money = money;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="线程类"><a href="#线程类" class="headerlink" title="线程类"></a>线程类</h3><h4 id="（执行取钱操作）"><a href="#（执行取钱操作）" class="headerlink" title="（执行取钱操作）"></a>（执行取钱操作）</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> ThreadSafety;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//线程类：将取钱行为看作是一条单独的线程创建</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DrawThread</span> <span class="keyword">extends</span> <span class="title">Thread</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//定义一个成员变量，接收账户对象</span></span><br><span class="line">    <span class="keyword">private</span> Account acc;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DrawThread</span><span class="params">(Account acc,String name)</span></span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(name);</span><br><span class="line">        <span class="keyword">this</span>.acc=acc;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">//执行取钱操作，每个用户取1000元</span></span><br><span class="line">        acc.DrawMoney(<span class="number">1000</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="开始执行"><a href="#开始执行" class="headerlink" title="开始执行"></a>开始执行</h3><h4 id="多用户共同取钱"><a href="#多用户共同取钱" class="headerlink" title="多用户共同取钱"></a>多用户共同取钱</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> ThreadSafety;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Demo1</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建一个允许共享的银行账户（可能会有多人同时使用）</span></span><br><span class="line">        Account acc = <span class="keyword">new</span> Account(<span class="number">111</span>, <span class="number">1000</span>);</span><br><span class="line">        <span class="comment">//创建多个线程去银行账户中取钱（多个线程操作一个资源）</span></span><br><span class="line">        Thread user1 = <span class="keyword">new</span> DrawThread(acc,<span class="string">&quot;user1&quot;</span>);</span><br><span class="line">        user1.start();</span><br><span class="line">        Thread user2 = <span class="keyword">new</span> DrawThread(acc,<span class="string">&quot;user2&quot;</span>);</span><br><span class="line">        user2.start();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<h3 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h3><h4 id="违反了正常取钱过程，存在严重安全问题"><a href="#违反了正常取钱过程，存在严重安全问题" class="headerlink" title="违反了正常取钱过程，存在严重安全问题"></a>违反了正常取钱过程，存在严重安全问题</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">user1用户执行取钱操作，余额充足，支付<span class="number">1000</span>元成功！</span><br><span class="line">user2用户执行取钱操作，余额充足，支付<span class="number">1000</span>元成功！</span><br><span class="line">user1用户结束操作，余额<span class="number">0.0</span>元</span><br><span class="line">user2用户结束操作，余额-<span class="number">1000.0</span>元</span><br></pre></td></tr></table></figure>


<h1 id="线程同步"><a href="#线程同步" class="headerlink" title="线程同步"></a>线程同步</h1><h3 id="也称同步代码块"><a href="#也称同步代码块" class="headerlink" title="也称同步代码块"></a>也称同步代码块</h3><h2 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h2><p>为了更好的解决线程安全问题的方案</p>
<h2 id="线程同步解决线程安全问题的核心思想"><a href="#线程同步解决线程安全问题的核心思想" class="headerlink" title="线程同步解决线程安全问题的核心思想"></a>线程同步解决线程安全问题的核心思想</h2><p>让多个线程实现先后依次访问共享资源，这样就解决了安全问题</p>
<h2 id="做法"><a href="#做法" class="headerlink" title="做法"></a>做法</h2><p>将共享资源上锁，每次只能一个线程进入访问完毕之后，其他线程才能进来</p>
<h2 id="三种同步（上锁）方式"><a href="#三种同步（上锁）方式" class="headerlink" title="三种同步（上锁）方式"></a>三种同步（上锁）方式</h2><ol>
<li>同步代码块</li>
<li>同步方法</li>
<li>Lock显式锁</li>
</ol>
<h2 id="同步代码块"><a href="#同步代码块" class="headerlink" title="同步代码块"></a>同步代码块</h2><h3 id="作用-1"><a href="#作用-1" class="headerlink" title="作用"></a>作用</h3><p>将出现线程安全问题的核心代码上锁，每次只允许一个线程进入，执行完毕之后自动解锁，其他线程才能进来执行</p>
<h3 id="格式"><a href="#格式" class="headerlink" title="格式"></a>格式</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span>(锁对象)&#123;</span><br><span class="line">    <span class="comment">// 访问共享资源的核心代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="锁对象"><a href="#锁对象" class="headerlink" title="锁对象"></a>锁对象</h4><p>理论上可以是任意的“唯一”对象即可</p>
<h4 id="原则上"><a href="#原则上" class="headerlink" title="原则上"></a>原则上</h4><p>锁对象建议使用共享资源  </p>
<pre><code>- 在实例方法中建议使用this作为锁对象，此时this正好是共享资源（使用前提代码必须高度面向对象）
- 在静态方法中建议使用**类名.class**字节码作为锁对象
</code></pre>
<h4 id="将上文中的取款行为进行上锁操作"><a href="#将上文中的取款行为进行上锁操作" class="headerlink" title="将上文中的取款行为进行上锁操作"></a>将上文中的取款行为进行上锁操作</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">DrawMoney</span><span class="params">(<span class="keyword">int</span> m)</span></span>&#123;</span><br><span class="line">    <span class="comment">//判断取钱的用户</span></span><br><span class="line">    String name =Thread.currentThread().getName();</span><br><span class="line">    <span class="comment">//判断余额是否充足</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">//将取款行为上锁(使用this表示锁住的对象是当前账户)</span></span><br><span class="line">    <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (Money &gt;= m) &#123;</span><br><span class="line">            <span class="comment">//输出取钱结果</span></span><br><span class="line">            System.out.println(name + <span class="string">&quot;用户执行取钱操作，余额充足，支付&quot;</span> + m + <span class="string">&quot;元成功！&quot;</span>);</span><br><span class="line">            <span class="comment">//更新账户余额</span></span><br><span class="line">            Money -= m;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">//余额不足，取钱失败</span></span><br><span class="line">            System.out.println(name + <span class="string">&quot;用户执行取钱操作，余额不足，支付失败！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(name + <span class="string">&quot;用户结束操作，余额&quot;</span> + Money + <span class="string">&quot;元&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="上锁后的运行结果"><a href="#上锁后的运行结果" class="headerlink" title="上锁后的运行结果"></a>上锁后的运行结果</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">user1用户执行取钱操作，余额充足，支付<span class="number">1000</span>元成功！</span><br><span class="line">user1用户结束操作，余额<span class="number">0.0</span>元</span><br><span class="line">user2用户执行取钱操作，余额不足，支付失败！</span><br><span class="line">user2用户结束操作，余额<span class="number">0.0</span>元</span><br></pre></td></tr></table></figure>

<h2 id="同步方法"><a href="#同步方法" class="headerlink" title="同步方法"></a>同步方法</h2><h3 id="作用-2"><a href="#作用-2" class="headerlink" title="作用"></a>作用</h3><p>把出现线程安全问题的和新方法锁起来，每次只允许一个线程进入访问，其他线程必须在方法外面等待</p>
<h3 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h3><p>直接给方法加上修饰符synchronized</p>
<h3 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h3><p>同步方法的原理和同步代码块的底层原理其实是完全一样的，只是同步方法是把整个方法的代码都锁起来的。</p>
<p>同步方法的底层也是有锁对象的：</p>
<ul>
<li>在实例方法中默认使用this作为锁对象</li>
<li>在静态方法中默认使用<strong>类名.class</strong>字节码作为锁对象</li>
</ul>
<h2 id="Lock显式锁"><a href="#Lock显式锁" class="headerlink" title="Lock显式锁"></a>Lock显式锁</h2><p>java.util.current.locks.lock机制提供了比synchronized代码块和synchronized同步方法更广泛的锁定操作</p>
<p>二者具有的功能Lock都有，除此之外功能更加强大</p>
<h3 id="Lock锁也称同步锁"><a href="#Lock锁也称同步锁" class="headerlink" title="Lock锁也称同步锁"></a>Lock锁也称同步锁</h3><p>其将加锁与释放锁的过程方法化了，如下：</p>
<ul>
<li>加锁：public void lock()</li>
<li>释放锁：public void unlock()</li>
</ul>
<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> ThreadSafety;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.Lock;</span><br><span class="line"><span class="keyword">import</span> java.util.concurrent.locks.ReentrantLock;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义账户类</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Account</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> cardID;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> Money;</span><br><span class="line">    <span class="comment">//在账户中创建锁对象</span></span><br><span class="line">    <span class="comment">//由于账户对象对于某个调用者是唯一的，所以锁对象对于某个调用者也是唯一的</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Lock lock=<span class="keyword">new</span> ReentrantLock();  <span class="comment">//加上final关键字是防止锁的唯一性被破坏，不加一般也可以正常运行</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">DrawMoney</span><span class="params">(<span class="keyword">int</span> m)</span></span>&#123;</span><br><span class="line">        String name =Thread.currentThread().getName();</span><br><span class="line"></span><br><span class="line">        lock.lock();  <span class="comment">//上锁</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (Money &gt;= m) &#123;</span><br><span class="line">                System.out.println(name + <span class="string">&quot;用户执行取钱操作，余额充足，支付&quot;</span> + m + <span class="string">&quot;元成功！&quot;</span>);</span><br><span class="line">                Money -= m;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(name + <span class="string">&quot;用户执行取钱操作，余额不足，支付失败！&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(name + <span class="string">&quot;用户结束操作，余额&quot;</span> + Money + <span class="string">&quot;元&quot;</span>);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();   <span class="comment">//解锁    </span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        * 在这里将整个执行代码放到try...catch结构里的原因是避免锁死的现象产生</span></span><br><span class="line"><span class="comment">        * 如果不用try...catch直接将解锁放到顺序执行的代码中，一旦代码报错程序中止运行</span></span><br><span class="line"><span class="comment">        * 就会导致解锁代码无法执行，对象被锁死</span></span><br><span class="line"><span class="comment">        * 所以采用try...catch并将解锁代码放到一定执行的finally中就可以避免这种情况</span></span><br><span class="line"><span class="comment">        * 即使报错，解锁行为也会正常运行</span></span><br><span class="line"><span class="comment">        * */</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Account</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Account</span><span class="params">(<span class="keyword">int</span> cardID, <span class="keyword">double</span> money)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cardID = cardID;</span><br><span class="line">        Money = money;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getCardID</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cardID;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCardID</span><span class="params">(<span class="keyword">int</span> cardID)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.cardID = cardID;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">getMoney</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Money;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMoney</span><span class="params">(<span class="keyword">double</span> money)</span> </span>&#123;</span><br><span class="line">        Money = money;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h2><ul>
<li>线程安全的程序，性能差</li>
<li>线程不安全的程序，性能较好。在开发中假如并不会存在多线程安全问题，一般采用线程不安全的设计</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">Ywrby</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://ywrby.cn/2021/03/03/3-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%EF%BC%8C%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/">http://ywrby.cn/2021/03/03/3-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%EF%BC%8C%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="/img/83821828_p0.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/03/03/4-%E7%BA%BF%E7%A8%8B%E9%80%9A%E4%BF%A1%EF%BC%8C%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81/"><img class="prev-cover" src="/img/80857290_p0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">4-线程通信，线程状态</div></div></a></div><div class="next-post pull-right"><a href="/2021/03/03/2-%E5%A4%9A%E7%BA%BF%E7%A8%8B/"><img class="next-cover" src="/img/67888138_p0.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">2-多线程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2021/07/27/1-JVM%E5%9F%BA%E7%A1%80/" title="1-JVM基础"><img class="cover" src="/img/illust_3518827_20191113_165540.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-07-27</div><div class="title">1-JVM基础</div></div></a></div><div><a href="/2021/03/03/1-%E5%BC%82%E5%B8%B8/" title="1-异常"><img class="cover" src="/img/72124553_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">1-异常</div></div></a></div><div><a href="/2021/03/03/10-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8/" title="10-方法引用"><img class="cover" src="/img/72175872_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">10-方法引用</div></div></a></div><div><a href="/2021/03/03/11-Stream%E6%B5%81/" title="11-Stream流"><img class="cover" src="/img/72124553_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">11-Stream流</div></div></a></div><div><a href="/2021/03/03/12-File%E7%B1%BB/" title="12-File类"><img class="cover" src="/img/68304874_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">12-File类</div></div></a></div><div><a href="/2021/03/03/13-%E9%80%92%E5%BD%92/" title="13-递归"><img class="cover" src="/img/83821828_p0.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-03</div><div class="title">13-递归</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> Comment</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/ywrby.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ywrby</div><div class="author-info__description">Students majoring in CS at SWU</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">127</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">Tags</div><div class="length-num">22</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/ywrby"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="mailto:ywrby0214@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/353923033" target="_blank" title="Bilibili"><i class="fas fa-file-video"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2278431384&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://twitter.com/ywrby1" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="https://www.facebook.com/profile.php?id=100033741068822" target="_blank" title="Facebook"><i class="fab fa-facebook"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>Announcement</span></div><div class="announcement_content">Less is more</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98"><span class="toc-number">1.</span> <span class="toc-text">线程安全问题</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%93%B6%E8%A1%8C%E5%8F%96%E9%92%B1%E9%97%AE%E9%A2%98"><span class="toc-number">1.1.</span> <span class="toc-text">银行取钱问题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%93%B6%E8%A1%8C%E8%B4%A6%E6%88%B7%E7%B1%BB"><span class="toc-number">1.1.1.</span> <span class="toc-text">银行账户类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89%E8%B4%A6%E6%88%B7%E5%86%85%E5%AE%B9%EF%BC%8C%E5%AE%9A%E4%B9%89%E5%8F%96%E9%92%B1%E6%96%B9%E6%B3%95"><span class="toc-number">1.1.1.1.</span> <span class="toc-text">定义账户内容，定义取钱方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E7%B1%BB"><span class="toc-number">1.1.2.</span> <span class="toc-text">线程类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%EF%BC%88%E6%89%A7%E8%A1%8C%E5%8F%96%E9%92%B1%E6%93%8D%E4%BD%9C%EF%BC%89"><span class="toc-number">1.1.2.1.</span> <span class="toc-text">（执行取钱操作）</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%80%E5%A7%8B%E6%89%A7%E8%A1%8C"><span class="toc-number">1.1.3.</span> <span class="toc-text">开始执行</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%A4%9A%E7%94%A8%E6%88%B7%E5%85%B1%E5%90%8C%E5%8F%96%E9%92%B1"><span class="toc-number">1.1.3.1.</span> <span class="toc-text">多用户共同取钱</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C"><span class="toc-number">1.1.4.</span> <span class="toc-text">运行结果</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%BF%9D%E5%8F%8D%E4%BA%86%E6%AD%A3%E5%B8%B8%E5%8F%96%E9%92%B1%E8%BF%87%E7%A8%8B%EF%BC%8C%E5%AD%98%E5%9C%A8%E4%B8%A5%E9%87%8D%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98"><span class="toc-number">1.1.4.1.</span> <span class="toc-text">违反了正常取钱过程，存在严重安全问题</span></a></li></ol></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5"><span class="toc-number">2.</span> <span class="toc-text">线程同步</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B9%9F%E7%A7%B0%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-number">2.0.1.</span> <span class="toc-text">也称同步代码块</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8"><span class="toc-number">2.1.</span> <span class="toc-text">作用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5%E8%A7%A3%E5%86%B3%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98%E7%9A%84%E6%A0%B8%E5%BF%83%E6%80%9D%E6%83%B3"><span class="toc-number">2.2.</span> <span class="toc-text">线程同步解决线程安全问题的核心思想</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%81%9A%E6%B3%95"><span class="toc-number">2.3.</span> <span class="toc-text">做法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E7%A7%8D%E5%90%8C%E6%AD%A5%EF%BC%88%E4%B8%8A%E9%94%81%EF%BC%89%E6%96%B9%E5%BC%8F"><span class="toc-number">2.4.</span> <span class="toc-text">三种同步（上锁）方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-number">2.5.</span> <span class="toc-text">同步代码块</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8-1"><span class="toc-number">2.5.1.</span> <span class="toc-text">作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%BC%E5%BC%8F"><span class="toc-number">2.5.2.</span> <span class="toc-text">格式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%94%81%E5%AF%B9%E8%B1%A1"><span class="toc-number">2.5.2.1.</span> <span class="toc-text">锁对象</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8E%9F%E5%88%99%E4%B8%8A"><span class="toc-number">2.5.2.2.</span> <span class="toc-text">原则上</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B0%86%E4%B8%8A%E6%96%87%E4%B8%AD%E7%9A%84%E5%8F%96%E6%AC%BE%E8%A1%8C%E4%B8%BA%E8%BF%9B%E8%A1%8C%E4%B8%8A%E9%94%81%E6%93%8D%E4%BD%9C"><span class="toc-number">2.5.2.3.</span> <span class="toc-text">将上文中的取款行为进行上锁操作</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%8A%E9%94%81%E5%90%8E%E7%9A%84%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C"><span class="toc-number">2.5.2.4.</span> <span class="toc-text">上锁后的运行结果</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8C%E6%AD%A5%E6%96%B9%E6%B3%95"><span class="toc-number">2.6.</span> <span class="toc-text">同步方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8-2"><span class="toc-number">2.6.1.</span> <span class="toc-text">作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">2.6.2.</span> <span class="toc-text">使用方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8E%9F%E7%90%86"><span class="toc-number">2.6.3.</span> <span class="toc-text">原理</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lock%E6%98%BE%E5%BC%8F%E9%94%81"><span class="toc-number">2.7.</span> <span class="toc-text">Lock显式锁</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Lock%E9%94%81%E4%B9%9F%E7%A7%B0%E5%90%8C%E6%AD%A5%E9%94%81"><span class="toc-number">2.7.1.</span> <span class="toc-text">Lock锁也称同步锁</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.7.2.</span> <span class="toc-text">代码实现</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93%EF%BC%9A"><span class="toc-number">2.8.</span> <span class="toc-text">总结：</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）"><img src="/img/67888138_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="22-内存空间扩充（覆盖与交换）"/></a><div class="content"><a class="title" href="/2021/12/25/22-%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4%E6%89%A9%E5%85%85%EF%BC%88%E8%A6%86%E7%9B%96%E4%B8%8E%E4%BA%A4%E6%8D%A2%EF%BC%89/" title="22-内存空间扩充（覆盖与交换）">22-内存空间扩充（覆盖与交换）</a><time datetime="2021-12-25T08:15:49.000Z" title="Created 2021-12-25 16:15:49">2021-12-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理"><img src="/img/80857290_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="21-内存与内存管理"/></a><div class="content"><a class="title" href="/2021/12/19/21-%E5%86%85%E5%AD%98%E4%B8%8E%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="21-内存与内存管理">21-内存与内存管理</a><time datetime="2021-12-19T09:57:53.000Z" title="Created 2021-12-19 17:57:53">2021-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁"><img src="/img/81934649_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="20-死锁"/></a><div class="content"><a class="title" href="/2021/12/11/20-%E6%AD%BB%E9%94%81/" title="20-死锁">20-死锁</a><time datetime="2021-12-11T06:20:20.000Z" title="Created 2021-12-11 14:20:20">2021-12-11</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程"><img src="/img/72581222_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="19-管程"/></a><div class="content"><a class="title" href="/2021/11/28/19-%E7%AE%A1%E7%A8%8B/" title="19-管程">19-管程</a><time datetime="2021-11-28T08:39:08.000Z" title="Created 2021-11-28 16:39:08">2021-11-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）"><img src="/img/73604608_p0.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="18-信号量相关问题（吸烟者，读者-写者等）"/></a><div class="content"><a class="title" href="/2021/11/17/18-%E4%BF%A1%E5%8F%B7%E9%87%8F%E7%9B%B8%E5%85%B3%E9%97%AE%E9%A2%98%EF%BC%88%E5%90%B8%E7%83%9F%E8%80%85%EF%BC%8C%E8%AF%BB%E8%80%85-%E5%86%99%E8%80%85%E7%AD%89%EF%BC%89/" title="18-信号量相关问题（吸烟者，读者-写者等）">18-信号量相关问题（吸烟者，读者-写者等）</a><time datetime="2021-11-17T12:08:38.000Z" title="Created 2021-11-17 20:08:38">2021-11-17</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/img/83821828_p0.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Ywrby</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="Scroll To Comments"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="Back To Top"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">Local search</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.css"><script>(() => {
  document.querySelectorAll('#article-container span.katex-display').forEach(item => {
    btf.wrap(item, 'div', { class: 'katex-wrap'})
  })
})()</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'QkExI1n70lz2qs7pVpmFeKqp-gzGzoHsz',
      appKey: 'WhG61iDj96bflhu6CIpmE9V8',
      placeholder: 'Please leave your footprints',
      avatar: 'mp',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: false,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="5402995011" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-lrctype=0	data-order="random" data-preload="none" data-autoplay="true" muted></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>